import { Input, Table, Space, Button, Link, Drawer, Form, Select, Popconfirm, Message } from '@arco-design/web-react';
import { IconPlusCircle, IconSearch, IconEdit, IconMinusCircle } from '@arco-design/web-react/icon';
import { useState } from 'react';
import { fetchRoleList, fetchRoleAdd, fetchTreeList, fetchUpdateRoleRes } from '../../../../../api/common'
import { regExpConfig } from '../../../../../configs/regular.config'
const Option = Select.Option;
const formItemLayout = {
    wrapperCol: {
      span: 24,
    },
  };


function RoleList({state, setState}){
    const [addVisiable, setAddVisible] = useState(false);
    const [modifyVisiable, setModifyVisible] = useState(false);
    const [userState, setUserState] = useState({})
    const [roleId, nextRoleId] = useState(4567)
    const columns = [
        {
          title: '',
          dataIndex: '',
          render: (col, record, index) => (
           <div style={{position: 'relative'}}>
                <Link>
                    <Button type='text' onClick={()=>{
                        setState(state=>{
                            return{
                                ...state,
                                roleTree: {
                                    ...state.roleTree,
                                    loading: true
                                }
                            }
                        })
                        fetchTreeList({curRoleId: state.curRoleId},
                            (res)=>{
                                setState(state=>{
                                    return{
                                        ...state,
                                        roleTree: {
                                            ...state.roleTree,
                                            data: res.data.list,
                                            loading: false
                                        }
                                    }
                                })
                            },
                            (error)=>{
                                Message.error(error)
                            })
                    }}>{record.roleName}
                    </Button>
                    <span style={{position: 'absolute', right: '5px'}}>
                        <Button style={{padding: '0px'}}  
                            onClick={()=>{
                                setUserState(record)
                                setModifyVisible(true)}}><IconEdit />
                        </Button>&nbsp;&nbsp;&nbsp;
                        <Popconfirm
                            focusLock
                            title='删除？'
                            onOk={() => {
                                let tmp = [...state.roleList.data]
                                for(let i = 0; i < tmp.length; i++){
                                    if (tmp[i].id == record.id){
                                        tmp.splice(i, 1)
                                        break
                                    }
                                }
                                setState(state=>{
                                    return{
                                        ...state,
                                        roleList: {
                                            ...state.roleList,
                                            data: tmp
                                        }
                                    }
                                })
                                Message.info({
                                    content: '删除成功',
                                });
                            }}
                            onCancel={() => {
                                Message.error({
                                    content: '取消',
                                });
                            }}
                        >
                            <Button style={{padding: '0px'}}><IconMinusCircle /></Button>
                        </Popconfirm>
                        </span>
                </Link>
            </div>
          ),
        }
    ];
    function AddRole(){
        const [form] = Form.useForm();
        const [confirmLoading, setConfirmLoading] = useState(false);
        return(
            <div>
                <Drawer
                    width={314}
                    title={<span>添加角色 </span>}
                    visible={addVisiable}
                    confirmLoading={confirmLoading}
                    onOk={() => {
                    form.validate().then((data) => {
                        setConfirmLoading(true);
                        fetchRoleAdd({roleInfo: data},
                            (res)=>{
                                data.resources = []
                                data.id = roleId
                                nextRoleId(roleId=>roleId+1)
                                setState(state=>{
                                    return{
                                        ...state,
                                        roleList: {
                                            ...state.roleList,
                                            data: [
                                                ...state.roleList.data,
                                                data
                                            ]
                                        }
                                    }
                                })
                                Message.success('添加成功')
                                setAddVisible(false);
                                setConfirmLoading(false);
                            },
                            (error=>{
                                Message.error(error)
                                setConfirmLoading(false);
                            }))
                    }).catch(error=>{
                        Message.error('格式错误')
                        setConfirmLoading(false);
                    });
                    }}
                    onCancel={() => {
                    setAddVisible(false);
                    }}
                >
                    <Form {...formItemLayout} form={form} layout='vertical'>
                    <Form.Item label='角色名称' field='roleName' 
                        rules={[{ required: true , minLength: 2, maxLength: 6, message: '角色名必须在2-6之间'}]}>
                        <Input  />
                    </Form.Item>
                    <Form.Item label='角色排序' required field='sort' rules={[
                        { required: true },
                        { match: regExpConfig.isInt, message: '必须是数字' }
                        ]}>
                        <Input  />
                    </Form.Item>
                    {/* <Form.Item label='是否统计' field='count' rules={[{ required: true }]}>
                        <Select placeholder='Plear select' options={['是', '否']} />
                    </Form.Item> */}
                    </Form>
                </Drawer>
            </div>
        )
    }

    function ModifyRole(){
        const [form] = Form.useForm();
        const [confirmLoading, setConfirmLoading] = useState(false);
        return(
            <div>
                <Drawer
                    width={314}
                    title={<span>修改 </span>}
                    visible={modifyVisiable}
                    confirmLoading={confirmLoading}
                    onOk={() => {
                    form.validate().then((data) => {
                        setConfirmLoading(true);
                        fetchUpdateRoleRes({...data},
                            (res)=>{
                                // state.roleList.data
                                let tmp = [...state.roleList.data]
                                for(let i = 0; i < tmp.length; i++){
                                    if (tmp[i].id == userState.id){
                                        tmp[i] = {
                                            ...tmp[i],
                                            ...data
                                            
                                        }
                                        break
                                    }
                                }
                                setState(state=>{
                                    return{
                                        ...state,
                                        roleList: {
                                            ...state.roleList,
                                            data: tmp
                                        }
                                    }
                                })
                                Message.success(res.msg)
                                setModifyVisible(false);
                                setConfirmLoading(false);
                            },
                            (error)=>{
                                Message.error(error)
                                setConfirmLoading(false);
                        })
                    }).catch(error=>{
                        Message.error('数据格式不对')
                        setConfirmLoading(false);
                    });
                    }}
                    onCancel={() => {
                        setModifyVisible(false);
                    }}
                >
                    <Form {...formItemLayout} form={form} layout='vertical'>
                    <Form.Item label='角色名称' field='name' rules={[{ required: true }]} initialValue={userState.roleName}>
                        <Input  placeholder={userState.roleName}/>
                    </Form.Item>
                    <Form.Item label='角色排序' required field='sort' rules={[{ required: true }]} initialValue={userState.sort}>
                        <Input  placeholder={userState.sort}/>
                    </Form.Item>
                    {/* <Form.Item label='是否统计' field='count' rules={[{ required: true }]}>
                        <Select
                            placeholder='Please select'
                            onChange={(value) =>{}
                            }
                        >
                            {[{key: true, value: '是'}, {key: false, value: '否'}].map((option, index) => (
                            <Option key={option.key} value={option.key}>
                                {option.value}
                            </Option>
                            ))}
                        </Select>
                    </Form.Item> */}
                    </Form>
                </Drawer>
            </div>
        )
    }

    function keywordChange(value){
        // console.log(state)
        setState(state=>{
            return{
                ...state,
                roleList: {
                    ...state.RoleList,
                    keyword: value
                }
            }
        })
    }

    function searchRoleList(){
        setState(state=>{
            return{
                ...state,
                roleList: {
                    ...state.RoleList,
                    loading: true
                }
            }
        })
        fetchRoleList({keyword: state.roleList.keyword}, 
            (res)=>{
                setState(state=>{
                    return{
                        ...state,
                        roleList: {
                            ...state.roleList,
                            loading: false,
                            data: res.data.list
                        },
                    }
                })
            },
            (error)=>{
                Message.error(error)
            })
    }


    return(
        <div style={{boxSizing: 'border-box' ,position: 'relative', height: '100%', padding: '5px'}}>
            <div style={{position: 'absolute', top: '10px', left: '10px'}}>
                <Input
                    addAfter={<Button style={{padding: '0px'}} onClick={()=>{setAddVisible(true)}}><IconPlusCircle /></Button>}
                    suffix={<Button style={{padding: '0px'}} onClick={searchRoleList}><IconSearch /></Button>}
                    placeholder=''
                    // onChange={keywordChange}
                    style={{ width: 225, }}
                />
            </div>
            <div style={{position: 'absolute', top: '65px', width: '85%'}}>
                <Table columns={columns} 
                    loading={state.roleList.loading}
                    data={state.roleList.data} 
                    pagination={false}
                    showHeader={false}
                    borderCell={false}
                    style={{border: '0px'}}>
                </Table>
            </div>
            <AddRole />
            { modifyVisiable ? <ModifyRole /> : null }
        </div>
    )
}

export default RoleList